package com.sxhuayuan.parking.controller.agent;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.sxhuayuan.parking.controller.BaseController;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.domain.Setting.AccountLockType;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.service.AgentService;
import com.sxhuayuan.parking.utils.SettingUtils;

/**
 * 登录，退出
 */
@RestController("agentAuthenticationController")
@RequestMapping("/agent")
public class AuthenticationController extends BaseController {

	@Resource(name = "agentServiceImpl")
	AgentService agentService;

	/**
	 * 登入
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public RespMessage login(HttpServletRequest request) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			return RespMessage.builder().success().setDatas(subject.getSession().getId().toString()).build();
		}
		String loginFailure = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = "";
		switch (loginFailure) {
		case "org.apache.shiro.authc.UnknownAccountException":
			message = Message.LOGIN_ACCOUNT_INCORRECT; // 账户不存在
			break;
		case "org.apache.shiro.authc.DisabledAccountException":
			message = Message.LOGIN_DISABLED_ACCOUNT; // 是否启用
			break;
		case "org.apache.shiro.authc.LockedAccountException":
			message = Message.LOGIN_LOCKED_ACCOUNT; // 账号被锁定
			break;
		case "org.apache.shiro.authc.pam.UnsupportedTokenException":
			message = Message.LOGIN_UNSUPPORTED_TOKEN; // 验证码
			break;
		case "org.apache.shiro.authc.IncorrectCredentialsException":
			if (ArrayUtils.contains(SettingUtils.get().getAccountLockTypes(), AccountLockType.admin)) {
				message = Message.LOGIN_ACCOUNT_LOCK_COUNT;
			} else {
				message = Message.LOGIN_ACCOUNT_INCORRECT;// 密码错误
			}
			break;
		case "org.apache.shiro.authc.AuthenticationException":
			message = Message.LOGIN_ACCOUNT_AUTHENTICATION;
			break;
		default:
			message = Message.LOGIN_ACCOUNT_AUTHENTICATION;
			break;
		}
		return RespMessage.builder().error().setErr(message, SettingUtils.get().getAccountLockTime()).build();
	}

	@RequestMapping("/logout")
	public RespMessage logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return RespMessage.builder().success().build();
	}
}
